<template>
  <div ref="dashboardChart" style="width: 500px; height: 400px;"></div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  Concentration: {
    type: String,
    default: '0'
  }
});

const dashboardChart = ref(null);
let chartInstance = null;

const initChart = () => {
  if (!dashboardChart.value) return;
  chartInstance = echarts.init(dashboardChart.value);
  const option = {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        center: ['50%', '75%'],
        radius: '90%',
        min: 0,
        max: 2,
        splitNumber: 8,
        axisLine: {
          lineStyle: {
            width: 6,
            color: [
              [0.25, '#7CFFB2'],
              [0.5, '#58D9F9'],
              [0.75, '#FDDD60'],
              [1, '#FF6E76'],
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '12%',
          width: 20,
          offsetCenter: [0, '-60%'],
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          length: 12,
          lineStyle: {
            color: 'auto',
            width: 2
          }
        },
        splitLine: {
          length: 20,
          lineStyle: {
            color: 'auto',
            width: 5
          }
        },
        axisLabel: {
          color: '#464646',
          fontSize: 20,
          distance: -60,
          rotate: 'tangential',
          formatter: function (value) {
            if (value == 1.75) {
              return '极危';
            } else if (value ==1.25) {
              return '高度';
            } else if (value == 0.75) {
              return '中度';
            } else if (value == 0.25) {
              return '轻度';
            }
            return '';
        }
        },
        title: {
          offsetCenter: [0, '-10%'],
          fontSize: 20
        },
        detail: {
          fontSize: 30,
          offsetCenter: [0, '-35%'],
          valueAnimation: true,
          formatter: function (value) {
            return Math.round(value) + '';
          },
          color: 'inherit'
        },
        data: [
          {
            value: parseFloat(props.Concentration),
            name: '浓度'
          }
        ]
      }
    ]
  };
  chartInstance.setOption(option);
};

watch(() => props.Concentration, (newValue) => {
  if (chartInstance) {
    const concentrationValue = parseFloat(newValue) / 2;
    chartInstance.setOption({
      series: [{
        data: [{
          value: concentrationValue,
          name: '浓度'
        }]
      }]
    });
  }
});

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>

<style scoped>
div {
  width: auto;
}
</style>
